<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Pyscript Demo</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
        - pandas
        - scikit-learn
        - matplotlib
        - statsmodels
    </py-env>
</head>
<body>
<input  style="display:none;"  type="text" id="area" th:value="${teaShopOrder}"/>

<div id="plot" ></div>
</body>
</html>
<py-script output = "plot">
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import datetime
import random

data = str(document.getElementById("area").value);
prices_dates = []
for item in data.split(","):
    price = int(item.split("price=")[1].split(" ")[0])
    date_str = item.split("date=")[1].strip("]").strip()
    date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    prices_dates.append([price, date])
x = [item[1].date() for item in prices_dates]
y = [item[0] for item in prices_dates]
result = {}
for i in range(len(x)):
    if x[i] not in result:
        result[x[i]] = y[i]
    else:
        result[x[i]] += y[i]
x = list(result.keys())
y = list(result.values())
# 获取当前日期
current_date = x[-1]
# 生成未来10天的日期
future_dates = []
for i in range(10):
    future_date = current_date + datetime.timedelta(days = i + 1)
    future_datetime = datetime.datetime.combine(future_date, datetime.datetime.min.time())
    future_dates.append(future_datetime)
predict_date = np.array(x + future_dates)

z = {'Date':np.array(x), 'Money':np.array(y)}
df = pd.DataFrame(z)
df.set_index('Date', inplace=True)
df['Time'] = np.arange(len(x))

# 创建线性回归模型
linear = LinearRegression()
# 训练模型
x_train = df['Time'].values.reshape(-1, 1)
y_train = df['Money'].values.reshape(-1, 1)


model = linear.fit(x_train, y_train)
# 进行预测
x_test = pd.DataFrame(df['Time'].values.reshape(-1, 1))
y_pred = model.predict(x_test)

# 打印预测结果
plt.figure(figsize=(12, 5), dpi = 300)
plt.grid(alpha=0.8, linestyle = '--')
plt.plot(df.index, df['Money'], color='deepskyblue', label='Consumption Data')
plt.plot(df.index, y_pred, color = 'tomato')
plt.title('Curvilinear Regression')
plt.xlabel('Date')
plt.ylabel('Consumption')
plt.legend()
plt
</py-script>
